package com.taikang.hmp.frame.login.action.intface;

import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.taikang.hmp.frame.common.ErrorConstant;
import com.taikang.hmp.frame.common.TKException;
import com.taikang.hmp.frame.common.datastructre.Dto;
import com.taikang.hmp.frame.common.datastructre.support.BaseDto;
import com.taikang.hmp.frame.common.datastructre.support.ResponseDto;
import com.taikang.hmp.frame.common.properties.PropertiesHelper;
import com.taikang.hmp.frame.common.tools.SmsUtils;
import com.taikang.hmp.frame.common.tools.json.JsonHelper;
import com.taikang.hmp.frame.common.web.action.BaseAction;
import com.taikang.hmp.frame.common.web.mobilecheck.MobileCheckFactory;
import com.taikang.hmp.frame.common.web.remotecall.security.uidlimit.AppUidStatusFactory;
import com.taikang.hmp.frame.common.web.session.AppSessionFactory;
import com.taikang.hmp.frame.common.web.session.SessionBean;
import com.taikang.hmp.frame.login.service.ILoginService;
import com.taikang.hmp.frame.user.bean.AuthUserInfo;
/** 
 * 登录
 * author:qrp
 * time:2015年7月20日 上午11:14:54
 */
public class LoginAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;


	private static Logger logger = LoggerFactory.getLogger(LoginAction.class);

	
	private ILoginService      loginService;
	

	

	public ILoginService getLoginService() {
		return loginService;
	}

	public void setLoginService(ILoginService loginService) {
		this.loginService = loginService;
	}

	

	public String executeAction() {
		if ("regist".equals(requestDto.getMethod())) {
			return regist();
		} else if ("login".equals(requestDto.getMethod())) {
			return login();
		} else if ("identify".equals(requestDto.getMethod())) {
			return identify();
		} else if ("passreset".equals(requestDto.getMethod())) {
			return passreset();
		} else if ("login4Doctor".equals(requestDto.getMethod())) {
			return login4Doctor();
		} else {
			throw new TKException("no support method:" + requestDto.getMethod());
		}
	}
	
	/**
	 * 注册
	 */
	public String regist(){
		//
		boolean error = false;
		logger.info("-----------------------开始注册用户！");
		ResponseDto responseDto = new ResponseDto();
		
		
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto = super.appendRequestBase(paramDto, requestDto);
		String requestsource = requestDto.getRequestsource();
		
		String usn = paramDto.getAsString("username");
		List<AuthUserInfo> info = loginService.getLoginInfo(usn);
		//身份证号统一为大写X
		String personIdNo = paramDto.getAsString("idno");
		if(StringUtils.isNotEmpty(personIdNo)){
			personIdNo = personIdNo.toUpperCase();
			paramDto.put("idno", personIdNo);
		}
		//如果是非泰康医生临时用户，走之前的验证
		if(info.size() == 0){
			//用户名验证		
			if(loginService.check_usn_repeat(paramDto.getAsString("username"))){
				logger.info("-----------------------用户名验证未通过！");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_REGIST_OCUPATION);
			}
			//手机号验证未通过
			if(error == false && loginService.check_mobile_repeat(paramDto.getAsString("mobile"))){
				logger.info("-----------------------手机号验证未通过！");
				error = true;
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_EXISTS);
			}
		}
		//身份证验证
		if(error == false && loginService.check_idno_repeat(personIdNo)){
			logger.info("-----------------------身份证验证未通过！");
			error = true;
			responseDto.addErrorCode(ErrorConstant.HD_IDNO_IS_EXISTS);
		}
		
		if(error){
			super.setDataMap(responseDto);
			return SUCCESS;
		}
		
		//
		String uid = null;
		if(!error){
			//查询
			if(info.size() == 0){
				uid = loginService.saveRegistInfo(paramDto);
			}else if(info.get(0).getUser_type() == null){
				responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_EXISTS);
			}else if(info.get(0).getUser_type().equals("3")){
				paramDto.put("customerid", info.get(0).getCustom_id());
				paramDto.put("userid", info.get(0).getUser_id());
				loginService.updateRegistInfo(paramDto);
				uid = info.get(0).getUser_id();
			}
			logger.info("-----------------------保存注册信息成功！uid:"+uid);
		}
		if(StringUtils.isNotEmpty(uid)){
			//保存session
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			//保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid,requestsource);
			//
			responseDto.setSessionid(sessionId);
			responseDto.setUid(uid);
		}else{
			responseDto.addErrorCode(ErrorConstant.HD_REGIST_EXIST);
		}
		super.setDataMap(responseDto);
		
		logger.info("response json:"+JsonHelper.formatJson(responseDto.toJson()));
		return SUCCESS;
	}
	
	
	/**
	 * 登录
	 */
	public String login(){
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		
		//
		String usn = paramDto.getAsString("username");
		String pwd = paramDto.getAsString("password");
		List<AuthUserInfo> info = loginService.getLoginInfo(usn);
		if(info.size()>0){
			String userid = info.get(0).getUser_id();
			String requestsource = requestDto.getRequestsource();
			//密码一致
			if(pwd.equals(info.get(0).getUser_pwd())){
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				//
				responseDto.setSessionid(sessionId);
				responseDto.setUid(userid);
			}
			//密码不一致
			else{
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginFail(userid,requestsource);
				//
				responseDto.addErrorCode(ErrorConstant.HD_PASSWORD_ERR);
			}
		}else{
			responseDto.addErrorCode(ErrorConstant.HD_USER_NOT_EXIST);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	
	/**
	 * 获取手机验证码
	 */
	public String  identify(){
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		
		String mobile = paramDto.getAsString("mobile");
		if (StringUtils.isNotEmpty(mobile)) {
			String code = MobileCheckFactory.getInstance(requestDto.getRequestsource()).produceIdentifyCode(mobile);			
			String pattern = PropertiesHelper.appHelper.getValue("message.passreset.pattern");
			String msg = pattern.replace("code", code);
			//发送短信
//			SmsUtils.sendSms(mobile, msg);
			
			Dto dto = new BaseDto();
			dto.put("identify", code);
			responseDto.pushResultDto(dto);
		} else {
			responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NULL);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	/**
	 * 忘记密码
	 */
	public String passreset(){		
		//通用校验
		ResponseDto responseDto = new ResponseDto();
			
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		Dto info = loginService.updateUserPwd(paramDto);
		
		//验证码验证
		String identifycode = (String)paramDto.get("identifycode");
		String mobile = (String)paramDto.get("mobile");
		String requestsource = requestDto.getRequestsource();
		//验证验证码
//		if(!AppIdentifyCodeFactory.getInstance().checkCode(mobile, identifycode))
//		{
//			responseDto.addErrorCode(ErrorConstant.HD_IDENTIFYCODE_NOT_EXIST);
//		}else 
			if(!"0".equals(info.getAsString("mobileExist"))){
			Dto dto = new BaseDto();
			dto.put("username", info.getAsString("username"));
			List<Dto> ld = new ArrayList<Dto>();
			ld.add(dto);
			responseDto.setResultlist(ld);
			
			//保存session
			String  uid = info.getAsString("uid");
			SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
			String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
			//保存用户状态
			AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid,requestsource);
			//
			responseDto.setSessionid(sessionId);
			responseDto.setUid(uid);
		}else{
			responseDto.addErrorCode(ErrorConstant.HD_MOBILE_IS_NOT_EXISTS);
		}
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
	
	/**
	 * 登录【泰康医生】
	 */
	public String login4Doctor(){
		//通用校验
		ResponseDto responseDto = new ResponseDto();
		//获取参数
		requestDto.setSessionid("");
		requestDto.setUid("");
		Dto paramDto = requestDto.getRequestlist().get(0);
		paramDto.put("requestsource", requestDto.getRequestsource());
		
		String usn = paramDto.getAsString("username");
		List<AuthUserInfo> info = loginService.getLoginInfo(usn);
		String requestsource = requestDto.getRequestsource();//为泰康医生所加的登录接口，source为高糖的
		Dto resultDto = new BaseDto();
		if(info.size()>0){
			String type = info.get(0).getUser_type();
			if(type.equals("0")){
			    String userid = info.get(0).getUser_id();
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				//
				responseDto.setSessionid(sessionId);
				responseDto.setUid(userid);
				resultDto.put("state", "1");//已经是高糖用户
			}else if(type.equals("3")){
			    String userid = info.get(0).getUser_id();
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(userid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(userid,requestsource);
				//
				responseDto.setSessionid(sessionId);
				responseDto.setUid(userid);
				resultDto.put("state", "0");//已经是高糖用户
			}
		}else{
			//创建新的用户
			String uid = loginService.saveReg4Doctor(paramDto);
			logger.info("-----------------------【高糖4医生】保存注册信息成功！uid:"+uid);
			if(StringUtils.isNotEmpty(uid)){
				//保存session
				SessionBean sessionInfo = loginService.getCustomerBasicInfo(uid);
				String sessionId = AppSessionFactory.getInstance(requestDto.getRequestsource()).putSession(sessionInfo);
				//保存用户状态
				AppUidStatusFactory.getInstance(requestDto.getRequestsource()).loginSuccess(uid,requestsource);
				responseDto.setSessionid(sessionId);
				responseDto.setUid(uid);
				resultDto.put("state", "0");//未在高糖中注册
			}else{
				responseDto.addErrorCode(ErrorConstant.HD_USER_NOT_EXIST);
			}
		}
	    
		responseDto.pushResultDto(resultDto);
		super.setDataMap(responseDto);
		return SUCCESS;
	}
	
}
